package com.conduit.commands.prototype;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.enums.ResultCode;

public abstract class AbstractValidateValueCommand extends AbstractCommand {

	@Override
	public void executeWithArgs(String args) {
		// validate command syntax
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		// get commnad's arguments
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			String textInput = matcher.group(1).trim();
			String regex = matcher.group(2).trim();
			String expectedResult = matcher.group(3).trim();
			try {
				String fileContent = getFileContent(textInput);
				Matcher resultMatcher = Pattern.compile(regex).matcher(
						fileContent);
				if (resultMatcher.find()) {
					String actualResult = resultMatcher.group(1).trim();
					// output validation - not CaSe SeNsAtIvE
					if (expectedResult.equalsIgnoreCase(actualResult)) {
						setResult("The Value for Regex: " + regex + " in File "
								+ textInput + " was " + actualResult
								+ " as Expected");
						setResultCode(ResultCode.Successes);
					} else {
						setResult("The Value for Regex: " + regex + " in File "
								+ textInput + " was " + actualResult
								+ " and not " + expectedResult + " as Expected");
						setResultCode(ResultCode.Error);
					}
				} else { // could not find the regex in file
					setResult("Could not find regex " + regex + " in file "
							+ textInput);
					setResultCode(ResultCode.Error);
				}

			} catch (Exception e) {
				setResult(e.getMessage());
				setResultCode(ResultCode.Error);
			}
		}
	}

	protected abstract String getFileContent(String textInput) throws Exception;

}
